<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="商品分类" prop="categoryId">
      <el-select
      	v-model="dataForm.categoryId"
      	size="medium"
      	placeholder="选择商品类别"
      	style="width: 100%;"
      	clearable
      >
      	<el-option v-for="one in categoryList" :key="one.id" :label="one.name" :value="one.id" />
      </el-select>
    </el-form-item>
	<el-form-item label="商品名称" prop="name">
	  <el-input v-model="dataForm.name"></el-input>
	</el-form-item>
	<el-form-item label="商品简介" prop="detail">
	  <el-input v-model="dataForm.detail"></el-input>
	</el-form-item>
	<el-form-item label="商品库存" prop="stock">
	  <el-input v-model="dataForm.stock" ></el-input>
	</el-form-item>
	<el-form-item label="商品售价" prop="price">
	  <el-input v-model="dataForm.price" placeholder="请填写整数,单位-分"></el-input>
	</el-form-item>
    <el-form-item label="商品图片" prop="image">
     <el-upload
     	ref="upload"
     	:action="url"
     	list-type="picture-card"
     	accept=".jpg,.jpeg,.png"
     	with-credentials="true"
     	:before-upload="beforeUploadHandle"
     	:on-remove="removeHandle"
		>
		<img width="100%" v-if="this.dataForm.image" :src="this.dataForm.image" height="100%">
		<i v-else class="el-icon-plus"></i>
     </el-upload>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
		dialogVisible: false,
		pathes:[],
        dataForm: {
          id: null,
          name: null,
          image: null,
          detail: null,
          categoryId: null,
          price: null,
          stock: null,
          status: 1
        },
		pageIndex: 1,
		pageSize: 10,
		categoryList:[],
        dataRule: {
          name: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' }
          ],
          image: [
            { required: true, message: '商品图片不能为空', trigger: 'blur' }
          ],
          detail: [
            { required: true, message: '商品简介不能为空', trigger: 'blur' }
          ],
          categoryId: [
            { required: true, message: '商品类别不能为空', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '价格,单位-分不能为空', trigger: 'blur' }
          ],
          stock: [
            { required: true, message: '库存数量不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
		  this.$refs['upload'].clearFiles();
          this.$refs['dataForm'].resetFields();
		 	let data = {
		 		pageNum: this.pageIndex,
		 		pageSize: this.pageSize
		 	};
		 	this.$http.post('/admin/category/list',data).then(resp =>{
		 			let page = resp.data.page;
		 			let list = page.list;
		 			this.categoryList = list;
		 		});
          if (this.dataForm.id) {
            this.$http.get('/product/detail',{
					 params:{
					      id:id
					    }
				})
			.then(resp=>{
				this.dataForm.name = resp.data.product.name;
				this.dataForm.detail = resp.data.product.detail;
				this.dataForm.image = resp.data.product.image;
				this.dataForm.categoryId = resp.data.product.categoryId;
				this.dataForm.price = resp.data.product.price;
				this.dataForm.stock = resp.data.product.stock;
				this.dataForm.status = resp.data.product.status;
			});
          }
        })
      },
	  beforeUploadHandle(file){
		  const formData = new FormData();
		  				formData.append('files', file);
		  				formData.append('type', 'goods_photo')
		  				// 设置请求头
		  				const config = {
		  					headers: {
		  						'Content-Type': 'multipart/form-data'
		  					}
		  				};
		  				this.$http.post('/cos/uploadCosFile', formData, config).then(resp => {
		  					this.dataForm.image = resp.data.urls[0];
							this.pathes = resp.data.pathes;
							console.log('this.dataForm.image:',this.dataForm.image);
							console.log('pathes:',this.pathes);
		  					this.$message({
		  						message: '上传成功',
		  						type: 'success',
		  						duration: 1200
		  					})
		  				})
		  				return false;
	  },
	  removeHandle(file,fileList){
	  	let url = file.response.urls;
	  	let path = this.picList[url];
		this.$http.post('cos/deleteCosFile',{pathes: [path]}).then(resp=>{
			delete this.picList[url];
		});
	  },
	  cancel(){
		this.$http.post('/cos/deleteCosFile',{pathes:this.pathes}).then(resp=>{
		})
	  	this.visible = false;
	  	this.$refs['upload'].clearFiles();
	  },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
			  let data = {
				id:this.dataForm.id,
			  	categoryId: this.dataForm.categoryId,
			  	name: this.dataForm.name,
			  	detail: this.dataForm.detail,
			  	image: this.dataForm.image,
			  	price: this.dataForm.price,
			  	status: this.dataForm.status,
			  	stock: this.dataForm.stock
			  };
			  this.$http.post(`/admin/product/${!this.dataForm.id? 'add' : 'update'}`,data).then(resp=>{
				  if(resp.data.code == 200){
					  this.$message({
					  	message: '操作成功',
					  	type: 'success',
					  	duration: 1200
					  });
					  this.visible = false;
					  this.$emit('refreshDataList');
				  } else{
						this.$message({
							message: '操作失败',
							type: 'error',
							duration: 1200
						});
					}
			  });
          }
        })
      },
	   handlePictureCardPreview(file) {
	          this.url = file.url;
	          this.dialogVisible = true;
	        }
    }
  }
</script>
